package org.wejob.command;

import org.wejob.command.api.TaskHandler;
import org.wejob.web.WebClient;

import java.io.IOException;
import java.util.function.Consumer;

/*
 * 编码器--从命令队列中获取命令，编码为字节码ByteBuffer，写入SocketReadBufferQueue中
 * */
public class TaskHandlerImpl extends Thread implements TaskHandler<WebClient> {
    private String name;
    private volatile int TaskNum;
    private CoderRunnableQueue queue;
    private WebClient Running;
    private AbstractTaskDispatcher dispatcher;
    private Consumer consumer;

    TaskHandlerImpl(WebClient webClient, AbstractTaskDispatcher dispatcher, Consumer consumer) {
        this.Running = webClient;
        this.incrementTaskNum();
        this.dispatcher = dispatcher;
        this.consumer = consumer;
    }

    public void acceptTask(WebClient webClient) {
        if (this.queue == null) {
            this.queue = new CoderRunnableQueue();
        }
        this.queue.offer(webClient);
        this.incrementTaskNum();
    }

    public void removeTask(WebClient webClient) throws InterruptedException {
        synchronized (this.dispatcher) {
            //这里remove的只可能是running
            if (this.TaskNum == 1) {//移除完之后为0
                this.Running = null;
                this.TaskNum--;
                //todo 这里代码设计有问题
                this.dispatcher.toEmpty(this);
            }
            if (this.TaskNum > 1) {
                this.TaskNum--;
            }
        }

    }

    synchronized int getTaskNum() {
        return this.TaskNum;
    }

    synchronized void incrementTaskNum() {
        this.TaskNum++;
    }

    synchronized void decrementTaskNum() {
        this.TaskNum--;
    }

    public void handle(Consumer<WebClient> consumer) {
        for (; ; ) {
            if (this.TaskNum == 1) {
                if (this.Running == null) {
                    this.Running = queue.poll();
                }
                if (Running != null) {
                    consumer.accept(Running);
                }
                // todo 如果命令队列为空，会产生空循环；这里考虑要不要加入空循环处理
            } else if (this.TaskNum > 1) {
                queue.offer(this.Running);
                Running = queue.poll();
                if (Running != null) {
                    consumer.accept(Running);
                }

            } else {
                //线程存在但是队列为空，这种属于异常情况
            }
        }
    }

    public static void main(String[] args) throws IOException {

    }

    @Override
    public void run() {
        handle(this.consumer);
    }
}
